// pages/visa/visa_get/visa_get.js
const {globalData} = getApp()
  var network=require("../../../utils/network.js")
Page({
    data: {
        count:60,
        isChecked:false,
        userinfos:{},
        companyinfos:{},
        img:{},
        licence:{},
        frontID:{},
        backID:{},
        default_list:[],
        phone:'',
        errmsg:'',
        time:'发送授权码'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.getInitData()
    },
    getInitData(){
        wx.showLoading({
            title:'加载中',
            mask:true
        })
        let self=this
        network.GET({
            url:'/new/user/elec/apply/info',
            success:res=>{
                let data=res.data.data
                self.setData({
                    userinfos:data.apply_user_info,
                    companyinfos:data.company_info,
                    licence:{
                        src:data.company_info.business_license_path?data.company_info.business_license_path:"",
                        fileName:""
                    },
                    frontID:{
                        src:"../../../img/default.png"
                    },
                    backID:{
                        src:"../../../img/default.png"
                    }
                })
                wx.hideLoading()
            }
        })
    },
    testReg(e){
        this.setData({
            phone:e.detail.value
        })
        const reg=/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
        if(e.detail.value.trim()==''){
            this.setData({
                errmsg:'手机号码不能为空'
            })
        }
        if(e.detail.value.length!==0&&!reg.test(e.detail.value)){
            this.setData({
                errmsg:'手机号有误'
            })
        }
        if(reg.test(e.detail.value)){
            this.setData({
                errmsg:''
            })
        }   
    },
    sendCode(){ 
        const timer=setInterval(()=>{
            this.setData({
                count:this.data.count-1,
                time:'倒计时('+this.data.count+')s'
            })
            this.setData({
                time:'倒计时('+this.data.count+')s'
            })
            if(this.data.count<=0){
                clearInterval(timer)
                this.setData({
                    time:'重新获取'
                })
            }
        },1000)
        getApp().network.POST({
            url: '/new/send_code ',
            header: {'content-type': 'application/json'},
            params:{
                phone:this.data.phone,
                type:'elec_sign'
            },
            success:res=>{
                console.log(res)
                if(res.data.code==0){
                    wx.showToast({
                      title: '发送验证码成功',
                      icon:'success'
                    })
                }
            },
            fail:(err)=>{
                throw(err)
            }
        })
    },
    minus(){
        this.setData({
            count:this.data.count--
        })
    },
    errorimg(){
        this.setData({
            licence:{
                src:'../../../img/default.png'
            }
        })
    },
    chooseImageTap(e) {
        let _this = this
        wx.showActionSheet({
          itemList: ['本地上传', '拍照上传'],
          itemColor: '#000000',
          success: function (res) {
            if (res.tapIndex === 0) {
              _this.chooseWxImage('album', e.currentTarget.dataset.name)
            } else if (res.tapIndex === 1) {
              _this.chooseWxImage('camera', e.currentTarget.dataset.name)
            }
          },
          fail: function (err) {
            throw(err)
          }
        })
      },
      // (2)图片选择后的回调方法
      chooseWxImage(type, name) {
        const self = this
        let count = 1
        wx.chooseImage({
          count: count,
          sizeType: ['original', 'compressed'],
          sourceType: [type],
          success: function (res) {
            wx.showLoading({
              title: '图片上传中...',
              mask: true
            })
            let str = true
            self.upImg(res.tempFilePaths[0], str, name)
          },
          fail: function (err) {
            throw(err)
          }
        })
      },
      // (3)图片选择后的,上传到服务器
      upImg(path, str, name) {
        let self = this
        const header = {
          'content-type': 'multipart/form-data'
        }
        const loginInfo = (globalData && globalData.loginInfo) || wx.getStorageSync('loginInfo');
        if (loginInfo && loginInfo.cookie) {
          header["Cookie"] = loginInfo.cookie;
        }
        wx.uploadFile({
          url: globalData.api_url + `/new/pub/upload`,
          filePath: path,
          name: 'file',
          header: header,
          formData: {
              'type': 'confirm'
          },
          success: function (res) {
            let data = JSON.parse(res.data)
            if (data.code == 0) {
              self.setData({
                [name]: {
                    src: data.data.src,
                    fileName: data.data.file_name
                }
              })
              if (str) {
                wx.hideLoading()
              }
            } else {
              wx.hideLoading()
            }
          },
          fail: function () {
            console.error('上传图片失败')
            wx.hideLoading()
          }
        })
      },
    onSubmit(e){
        const formdatas={
            value:e.detail.value,
            legal_person:e.detail.value.username,
            legal_person_phone:e.detail.value.phone,
            id_card_font:this.data.frontID.src,
            id_card_reverse:this.data.backID.src,
            phone_code:e.detail.value.codes
        }
        const loginInfo = wx.getStorageSync('loginInfo');
        getApp().network.POST({
            url: '/new/user/elec/apply',
            data:formdatas,
            header: {
             'content-type': 'application/json',
             'Cookie':loginInfo.cookie
            }, 
            success:res=>{
                if(res.data.msg=="已经申领过电子签章"){
                  wx.showToast({
                      title: '已经申领过电子签章',
                      icon:'success'
                    })
                }
                if(res.data.msg=="申领成功"){
                    const companyinfos=JSON.stringify(this.data.companyinfos)
                    wx.navigateTo({
                      url: '../visa/visa_successpage/visa_successpage?companyinfos='+companyinfos,
                    })
                    getApp().globalData.visaState=true
                    wx.setStorageSync('visa_state', true)
                }
            },
            fail:err=>{
                throw(err)
            }
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
       
})